package com.weixing.oauth2.common.provider.error;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * 自定义处理401错误提示
 *
 * @Author: kfc
 * @Description: <br/>
 * Date:Create in 2019/8/13 15:44
 * @Modified By:
 */
public class Auth2ResponseExceptionTranslator  implements WebResponseExceptionTranslator ,AuthenticationEntryPoint {
    @Override
    public ResponseEntity translate(Exception e) {
        Throwable throwable = e.getCause();
        if (throwable instanceof InvalidTokenException) {
            return new ResponseEntity(ResultUtil.unauthorized(), HttpStatus.OK);
        }
        return new ResponseEntity(ResultUtil.unauthorized(ResultCodeEnum.CODE_10011001), HttpStatus.OK);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Throwable cause = authException.getCause();
        Result result;
        if(cause instanceof InvalidTokenException) {
            result = ResultUtil.error("无效token");
        }else{
            result = ResultUtil.error("无效token1111111111111");
        }
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            System.out.println("11111111111111111111111111111111111111");
            ObjectMapper mapper = new ObjectMapper();
            response.getWriter().write(mapper.writeValueAsString(result));
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}
